package org.tool.spring.utils.lang;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import org.tool.spring.application.ApplicationContextUtil;

import java.lang.annotation.Annotation;
import java.util.List;
import java.util.stream.Collectors;

import static cn.hutool.core.text.CharSequenceUtil.EMPTY;
import static org.common.constant.MagicValue.POINT;
import static org.common.constant.MagicValue.SPLIT_POINT;

/**
 * 项目包相关工具类
 *
 * @author 李坤
 * @date 2022/7/7 17:12
 */
public abstract class PackageUtil {

    /**
     * 获取存在给定注解的SpringBean的公共包地址
     *
     * @param annotation 给定注解
     *
     * @return 公共包地址
     */
    public static String getPackage(Class<? extends Annotation> annotation) {
        List<String> packagePaths = ApplicationContextUtil.getBeansWithAnnotation(annotation).values().stream()
                .map(value -> value.getClass().getPackage().getName()).collect(Collectors.toList());

        String result = EMPTY;
        if (CollectionUtil.isNotEmpty(packagePaths)) {
            String[] packageNames = packagePaths.get(0).split(SPLIT_POINT);

            for (String packageName : packageNames) {
                result = StrUtil.isEmpty(result) ? packageName : result + POINT + packageName;

                for (String packagePath : packagePaths) {
                    if (!packagePath.startsWith(result)) {
                        return result.substring(0, result.lastIndexOf(POINT));
                    }
                }
            }
        }
        return result;
    }

}
